package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.EmpListAdapter;
import com.example.administrator.yanfoxconn.bean.CyCarMessage;
import com.example.administrator.yanfoxconn.bean.CzKillCheckLv;
import com.example.administrator.yanfoxconn.bean.EmpFile;
import com.example.administrator.yanfoxconn.bean.FileName;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.CustomLruCacheUtils;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyGridView;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import taobe.tec.jcc.JChineseConvertor;

/**
 * 物流消殺車輛 維護及提交界面
 */
public class CyKillActivity extends BaseActivity implements View.OnClickListener{
    private final int MESSAGE_TOAST = 2;
    private final int MESSAGE_GET_LIST = 1;//tv賦值
    private final int MESSAGE_NOT_NET = 3;//網絡問題
    private final int MESSAGE_SET_MT_LIST=4;//給碼頭列表賦值
    private final int MESSAGE_SHOW_IMAGE = 5;//顯示圖片

    private static final int REQUEST_CAMERA_CODE = 11;
    private static final int REQUEST_PREVIEW_CODE = 22;
    private ArrayList<String> imagePaths = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPaths = new ArrayList<String>();//圖片壓縮后地址
    private ImageCaptureManager captureManager; // 相机拍照处理类

    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.btn_title_right)
    Button btnUp;//提交

    @BindView(R.id.tv_sq)
    TextView tvSq;//單號
    @BindView(R.id.tv_driver)
    TextView tvDriver;//司機
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;//車牌號
    @BindView(R.id.tv_card_id)
    TextView tvCardId;//身份證號
    @BindView(R.id.tv_area)
    TextView tvArea;//区域
    @BindView(R.id.tr_reason)
    TableRow trReason;
    @BindView(R.id.sp_reason)
    Spinner spReason;
    @BindView(R.id.tr_temp)
    TableRow trTemp;
    @BindView(R.id.et_temperature)
    EditText etTemperature;//體溫
    @BindView(R.id.tr_des)
    TableRow trDes;
    @BindView(R.id.et_description)
    EditText etDes;//異常描述
    @BindView(R.id.tr_mt)
    TableRow trMt;//碼頭
    @BindView(R.id.et_mt)
    EditText etMt;//碼頭
    @BindView(R.id.tr_list_mt)
    TableRow trListMt;//碼頭
    @BindView(R.id.lv_mt)
    MyListView lvMt;//碼頭列表
    @BindView(R.id.tv_photo)
    TextView tvPhoto;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;//空白图片占位
    @BindView(R.id.gv_photo)
    MyGridView gridView;//图片显示区域


    @BindView(R.id.ll_photo)
    LinearLayout llPhoto;//圖片
    private ViewGroup group;

    private GridAdapter gridAdapter;
    private int photoNum=3;

    private String[] qrResult;//掃碼結果
    private String type;//來向：cy 必須輸入體溫，cz 體溫不必須
    private CyCarMessage cyCarMessage;
    private List<CyCarMessage> cyCarMessageList;
    private String reason;
    private EmpListAdapter mAdapter;
    private List<String> teamList;
    private List<EmpFile> empFileList;
    private List<FileName> fileNameList;//圖片名稱
    Bitmap image = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cy_kill);
        ButterKnife.bind(this);

        tvTitle.setText("消殺點檢");
        btnUp.setVisibility(View.VISIBLE);
        btnUp.setText("提交");
        btnUp.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        ivEmpty.setOnClickListener(this);

        type = getIntent().getStringExtra("type");
        cyCarMessage = (CyCarMessage) getIntent().getSerializableExtra("carMessage");
        tvSq.setText(cyCarMessage.getAPPLY_NO());
        tvDriver.setText(cyCarMessage.getDRIVER_NAME());
        tvCarNum.setText(cyCarMessage.getCAR_NUM());
        tvCardId.setText(cyCarMessage.getDRIVER_CARD());
        tvArea.setText(cyCarMessage.getDOOR());
        if (FoxContext.getInstance().getType().equals("KG")){
            trReason.setVisibility(View.VISIBLE);
            trTemp.setVisibility(View.GONE);
            trDes.setVisibility(View.GONE);
            tvTitle.setText("稽核查驗");
            tvPhoto.setText("稽核照片");
            photoNum=1;
            getReason();
        }else if (FoxContext.getInstance().getType().equals("LS")){
            getMt();
            group = (ViewGroup) findViewById(R.id.ll_get_image);
            trMt.setVisibility(View.VISIBLE);
            photoNum=9;
            trReason.setVisibility(View.GONE);
            trTemp.setVisibility(View.GONE);
            trDes.setVisibility(View.GONE);
            tvTitle.setText("碼頭消殺");
            tvPhoto.setText("消殺照片");

            etMt.setTag("0");//用於判斷是否選擇門崗0;為未選擇,其他為選擇
            //搜索关键字
            etMt.addTextChangedListener(new TextWatcher() {

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }
                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    trListMt.setVisibility(View.VISIBLE);
                    String a = etMt.getText().toString().toUpperCase();
                    //调用适配器里面的搜索方法
                    mAdapter.SearchCity(a);
                }
                @Override
                public void afterTextChanged(Editable editable) {
                }

            });
        }

        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 3 ? 3 : cols;
        gridView.setNumColumns(cols);

        // preview
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePaths.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(CyKillActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(photoNum); // 最多选择照片数量，默认为1
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(CyKillActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });
    }
    public void getMt(){

        showDialog();
        String url = Constants.HTTP_LS_SAFEDATAQUREY_CMTS ;
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);

                Log.e("---------", "=getcarLog=fff===" + url);
                Gson gson = new Gson();
                String response = result;
                Log.e("---------", "result==fff===" + response);

                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        empFileList = new ArrayList<EmpFile>();
                        for (JsonElement type : array) {
                            EmpFile humi = gson.fromJson(type, EmpFile.class);
                            empFileList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_MT_LIST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    } else {
//                        isShowReturn = false;
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_TOAST;
                    message.obj = "無數據";
                    mHandler.sendMessage(message);
                }
                dismissDialog();
            }
        }.start();


    }
    private void getPhoto() {
        showDialog();
        String  url = Constants.HTTP_LS_SAFEDATAQUREY_MT + "?xs_no=" + cyCarMessage.getFEN_APPLY_NO()+"&xs_id="+cyCarMessage.getXS_ID();
        Log.e("-----","fff--"+url);
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);
                dismissDialog();
                Gson gson = new Gson();
//                Log.e("---fff--result----", result.toString());

                if (result != null) {
                    Log.e("---fff--result----", result.toString());
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray array = jsonObject.get("data").getAsJsonArray();


                        fileNameList = new ArrayList<FileName>();
                        for (JsonElement type1 : array) {
                            FileName humi1 = gson.fromJson(type1, FileName.class);
                            fileNameList.add(humi1);
                        }
                        for (int i = 0; i < fileNameList.size(); i++) {
                            Log.e("-----fileNameList----", fileNameList.get(i).getREC_NAME().toString());
//                            stringVoidBitmapAsyncTask.execute(fileNameList.get(i).getExce_filename1());
                            image = getBitmapFromServer(fileNameList.get(i).getREC_NAME());

                            Message messageFile = new Message();
                            messageFile.what = MESSAGE_SHOW_IMAGE;
                            messageFile.obj = image;
                            mHandler.sendMessage(messageFile);
                        }
                    } else {
                        Log.e("--------", "dd=jsonObject.get(\"errMessage\").getAsString()==" + jsonObject.get("errMessage").getAsString());
//                                ToastUtils.showShort(RouteListActivity.this, jsonObject.get("errMessage").getAsString());
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_TOAST;
                    message.obj = "請求不成功";
                    mHandler.sendMessage(message);
                }

            }
        }.start();
    }
    private String result="";
    public void getReason(){
        showDialog();
       String url = Constants.HTTP_GET_REASON ;
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);

                Log.e("---------", "=getcarLog=fff===" + url);
                Gson gson = new Gson();
                String response = result;
                Log.e("---------", "result==fff===" + response);

                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("result").getAsJsonArray();
                        cyCarMessageList = new ArrayList<CyCarMessage>();
                        for (JsonElement type : array) {
                            CyCarMessage humi = gson.fromJson(type, CyCarMessage.class);
                            cyCarMessageList.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_GET_LIST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    } else {
//                        isShowReturn = false;
                        Message message = new Message();
                        message.what = MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = MESSAGE_TOAST;
                    message.obj = "無數據";
                    mHandler.sendMessage(message);
                }
                dismissDialog();
            }
        }.start();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.iv_empty:
                PhotoPickerIntent intent = new PhotoPickerIntent(CyKillActivity.this);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(photoNum); // 最多选择照片数量，默认为1
                intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态

                startActivityForResult(intent, REQUEST_CAMERA_CODE);
                break;
            case R.id.btn_title_right:
                if (FoxContext.getInstance().getType().equals("KG")){
                    upReason();
                }else if (FoxContext.getInstance().getType().equals("LS")){
                    if (etMt.getTag().toString().equals("0")){
                        //請選擇碼頭
                        ToastUtils.showShort(CyKillActivity.this, "請選擇碼頭!");
                        return;
                    }else{
                        upLSMTReason();
                    }
                }else{
                if (etTemperature.getText().toString().equals("")) {
                    ToastUtils.showShort(this, "請填寫溫度");
                }else if(!etTemperature.getText().toString().equals("")&&Float.parseFloat(etTemperature.getText().toString())>42||etTemperature.getText().toString().substring(etTemperature.getText().toString().length()-1).equals(".")){
                        ToastUtils.showShort(this, "請填寫正確格式溫度");
                }else if(FoxContext.getInstance().getName().equals("")){
                    ToastUtils.showShort(this, "賬號異常，請重新登錄");
                } else if (imagePaths==null) {
                    ToastUtils.showShort(this, "請選擇圖片");
                }else{

                normal2();
                }}
                break;
        }
    }

    public void normal2() {
        Log.e("--------------------"," btnUp.setClickable(false);" +
                "");
        btnUp.setClickable(false);
        if (FoxContext.getInstance().getLoginId().equals("")) {
            ToastUtils.showShort(this, "登錄超時,請重新登陸");
        }
        final String url = Constants.HTTP_XS_CY_SAFEDATASAVE_SERVLET; //此處寫上自己的URL
        final Map<String, String> paramMap = new HashMap<String, String>(); //文本資料全部添加到Map裡
        showDialog();

        paramMap.put("xs_id", cyCarMessage.getFEN_APPLY_NO());
        paramMap.put("xs_no", cyCarMessage.getFEN_APPLY_NO());
        paramMap.put("xs_tw", etTemperature.getText().toString());
        paramMap.put("xs_remark", etDes.getText().toString());
        paramMap.put("xs_recorder", FoxContext.getInstance().getName());

        final Map<String, File> fileMap = new HashMap<String, File>(); //檔全部添加到Map裡

        for (int i = 0; i < imagePaths.size(); i++) {
            File pictureFile = new File(imagePaths.get(i)); //通過路徑獲取檔
//            fileMap.put("file" + i, pictureFile);//添加第一個文件
            final String pic_path = imagePaths.get(i);
            String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
            String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
            //getFilesDir().getAbsolutePath()+"compressPic.jpg";
            //调用压缩图片的方法，返回压缩后的图片path
            final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 80);
            final File compressedPic = new File(compressImage);
            imgZipPaths.add(i,compressImage);
            Log.e("----com---",compressImage);
            if (compressedPic.exists()) {
                Log.e("-------------","图片压缩上传");
                fileMap.put("file"+i,compressedPic);//添加第一個文件

            }else{//直接上传
                fileMap.put("file"+i,pictureFile);
            }
        }

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                try {

                    HttpURLConnection b = HttpConnectionUtil.doPostPicture(url, paramMap, fileMap);
                    Log.e("---------", "==fff===" + url);
                    if (b!=null){

                        Log.e("---------", "==fff===" + b);
                        if (b.getResponseCode()==200){
                            FileUtil.deletePhotos(CyKillActivity.this);
//                            delete(imagePaths);
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = "上傳成功";
                            mHandler.sendMessage(message);
                            dismissDialog();
                            finish();
                        }else{
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = "上傳失敗";
                            mHandler.sendMessage(message);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(CyKillActivity.this);
                }
            }
        }.start();
    }
    //上傳物流車輛稽核
    public void upReason() {
        btnUp.setClickable(false);
        if (FoxContext.getInstance().getLoginId().equals("")) {
            ToastUtils.showShort(this, "登錄超時,請重新登陸");
        }
        final String url = Constants.HTTP_UP_REASON; //此處寫上自己的URL

        JsonObject object = new JsonObject();


        object.addProperty("area", cyCarMessage.getDOOR());
        object.addProperty("reason", reason);
        object.addProperty("order_id", cyCarMessage.getFEN_APPLY_NO());
        object.addProperty("creator", FoxContext.getInstance().getName());
        object.addProperty("driver", cyCarMessage.getDRIVER_NAME());
        object.addProperty("car_id", cyCarMessage.getCAR_NUM());


        JsonArray photoArray = new JsonArray();

        if (imagePaths != null && imagePaths.size() != 0) {
            for (int k = 0; k < imagePaths.size(); k++) {
                final String pic_path = imagePaths.get(k);
                String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                String _path = sign_dir + File.separator + System.currentTimeMillis() + 0 + k + ".jpg";
                Log.e("------_path-------", _path);
                final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 50);
                Log.e("-------compressImage------", compressImage);
                String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
                Log.e("-------picBase64Code-------", "====" + picBase64Code);
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("file", picBase64Code);
                photoArray.add(jsonObject1);
            }
        } else {
        }
        object.add("photo", photoArray);

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("---------", "==fff===" + url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                            finish();
                        } else {
                            Log.e("-----------", "result==" + result);
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    } else {
                        Message message = new Message();
                        message.what = MESSAGE_NOT_NET;
                        mHandler.sendMessage(message);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    FileUtil.deletePhotos(CyKillActivity.this);
                }
            }
        }.start();
    }
    //上傳碼頭LS流車輛稽核
    public void upLSMTReason() {
        btnUp.setClickable(false);
        if (FoxContext.getInstance().getLoginId().equals("")) {
            ToastUtils.showShort(this, "登錄超時,請重新登陸");
        }
        final String url = Constants.HTTP_LS_SAFEDATASAVE_GAI; //此處寫上自己的URL

        final Map<String, String> paramMap = new HashMap<String, String>(); //文本資料全部添加到Map裡
        showDialog();

        paramMap.put("xs_id", cyCarMessage.getXS_ID());
        paramMap.put("xs_no", cyCarMessage.getFEN_APPLY_NO());
        paramMap.put("xs_recorder", FoxContext.getInstance().getLoginId());
        paramMap.put("car_num", cyCarMessage.getCAR_NUM());
        paramMap.put("in_datex", cyCarMessage.getIN_DATEX());
        paramMap.put("matou", etMt.getText().toString());

        final Map<String, File> fileMap = new HashMap<String, File>(); //檔全部添加到Map裡

        for (int i = 0; i < imagePaths.size(); i++) {
            File pictureFile = new File(imagePaths.get(i)); //通過路徑獲取檔
//            fileMap.put("file" + i, pictureFile);//添加第一個文件
            final String pic_path = imagePaths.get(i);
            String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
            String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
            //getFilesDir().getAbsolutePath()+"compressPic.jpg";
            //调用压缩图片的方法，返回压缩后的图片path
            final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 80);
            final File compressedPic = new File(compressImage);
            imgZipPaths.add(i,compressImage);
            Log.e("----com---",compressImage);
            if (compressedPic.exists()) {
                Log.e("-------------","图片压缩上传");
                fileMap.put("file"+i,compressedPic);//添加第一個文件

            }else{//直接上传
                fileMap.put("file"+i,pictureFile);
            }
        }

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                try {

                    HttpURLConnection b = HttpConnectionUtil.doPostPicture(url, paramMap, fileMap);
                    Log.e("---------", "==fff===" + url);
                    if (b!=null){

                        Log.e("---------", "==fff===" + b);
                        if (b.getResponseCode()==200){
                            FileUtil.deletePhotos(CyKillActivity.this);
//                            delete(imagePaths);
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = "上傳成功";
                            mHandler.sendMessage(message);
                            dismissDialog();
                            finish();
                        }else{
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = "上傳失敗";
                            mHandler.sendMessage(message);
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(CyKillActivity.this);
                }
            }
        }.start();
    }
    Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_SET_MT_LIST://給碼頭列表賦值
                            teamList = new ArrayList<>();
        for (int i = 0;i<empFileList.size();i++){
            teamList.add(change1(empFileList.get(i).getNAME()));
        }

        mAdapter = new EmpListAdapter(CyKillActivity.this,teamList,"ls");
        lvMt.setAdapter(mAdapter);

        //稽核門崗列表,選中后1:tit賦值,2:列表隱藏
        mAdapter.OnClickSetText(new EmpListAdapter.OnClickSetText() {
            @Override
            public void OnClickxt(String tit) {
                etMt.setText(tit);
                etMt.setTag(tit);
//                paramMap.put("mengang", empFileList.get(position).getID());
                mAdapter.SearchCity("");
                trListMt.setVisibility(View.GONE);
            }
            @Override
            public void OnClicktv(String tit, String tv) {
            }
        });
                    getPhoto();
                    break;
                case MESSAGE_TOAST://Toast彈出
                    ToastUtils.showShort(CyKillActivity.this,msg.obj.toString());
                    break;
                case MESSAGE_GET_LIST:
                    List<String> areaName=new ArrayList<>();
                    for (int i = 0;i<cyCarMessageList.size();i++){
                        areaName.add(cyCarMessageList.get(i).getNAME());
                    }
                    //稽核課隊下拉列表選擇
                    spReason.setAdapter(new ArrayAdapter<String>(CyKillActivity.this, android.R.layout.simple_list_item_1, areaName));
                    spReason.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            reason=areaName.get(position);
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                    break;

                case MESSAGE_NOT_NET:
                    ToastUtils.showLong(CyKillActivity.this, "網絡問題請退出重試!");

                    break;
                case MESSAGE_SHOW_IMAGE:
                    llPhoto.setVisibility(View.VISIBLE);
                    addGroupImage((Bitmap) msg.obj);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    //刪除已上傳的照片，新方法
//    public void delete(List<String> imagePath){
//        for (int i = 0;i<imagePath.size();i++){
//            String where=MediaStore.Audio.Media.DATA+" like \""+imagePath.get(i)+"%"+"\"";
//            int id=  this.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,where,null);
//
////            deleteDir(imagePath.get(i));
//            Log.e("--------------------","id=="+id);
//        }
//    }

    @Override//圖片回傳
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();

                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths);
                        Log.e("==========", paths.get(photoNum));
                    }
                    break;

            }
        }
    }
    //圖片賦值
    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths == null) {
            imagePaths = new ArrayList<>();
        }
        imagePaths.clear();
        imagePaths.addAll(paths);

        if (paths.size() > 0) {
            ivEmpty.setVisibility(View.GONE);
        } else {
            ivEmpty.setVisibility(View.VISIBLE);
        }

        try {
            JSONArray obj = new JSONArray(imagePaths);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapter == null) {
            gridAdapter = new GridAdapter(imagePaths);
            gridView.setAdapter(gridAdapter);
            Log.e("----------------", "ddd==" + imagePaths.size());
        } else {
            gridAdapter.notifyDataSetChanged();
        }

    }
    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == photoNum) {
                return photoNum;
            } else {
                return listUrls.size() + 1;
            }
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }
            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == photoNum) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(CyKillActivity.this)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }
    //繁体转成简体
    public String change1(String changeText) {
        try {
            JChineseConvertor jChineseConvertor = JChineseConvertor
                    .getInstance();
            changeText = jChineseConvertor.t2s(changeText);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return changeText;
    }
    //加載圖片
    public static Bitmap getBitmapFromServer(String imagePath) {
        String imgPath = Constants.HTTP_XS_GET_IMG + imagePath;

        Log.e("---------", "==fff===" + imgPath);
        HttpGet get = new HttpGet(imgPath);
        HttpClient client = new DefaultHttpClient();
        Bitmap bitmap = null;
        CustomLruCacheUtils customLruCache = CustomLruCacheUtils.getInstance();
        bitmap = customLruCache.getBitmapFromMemoryCache(imagePath);
        //先从缓存中读取图片，如果缓存中不存在，再请求网络，从网络读取图片添加至LruCache中
        //启动app后第一次bitmap为null,会先从网络中读取添加至LruCache,如果app没销毁,再执行读取图片操作时
        //就会优先从缓存中读取
        if (bitmap == null) {
            //从网络中读取图片数据

            HttpResponse response = null;
            try {
                response = client.execute(get);
                Log.e("---------", "==fff===" + response);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();

                bitmap = BitmapFactory.decodeStream(is);   // 关键是这句代码
                customLruCache.addBitmapToMemoryCache(imagePath, bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    //顯示圖片
    private void addGroupImage(Bitmap bitmap) {
        WindowManager wm = this.getWindowManager();

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        Log.e("--------", "width==" + width + "==height==" + height);
        ImageView imageView = new ImageView(this);
//        imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));  //设置图片宽高
        imageView.setLayoutParams(new ViewGroup.LayoutParams(width, width));  //设置图片宽高

        imageView.setImageBitmap(bitmap); //图片资源
        group.addView(imageView); //动态添加图片
    }
}
